package edu.jxufe.nb112.blog.web.controller.fileupload;

import edu.jxufe.nb112.blog.core.persist.service.user.SysConfigService;
import edu.jxufe.nb112.blog.web.controller.TestController;
import edu.jxufe.nb112.common.model.ResponseEntity;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author hong.zheng
 * @Description
 * @date 2017-12-18-19:56
 **/
@Controller
@RequestMapping(value = "fileUpload")
public class FileUploadController {

    private final static Logger LOG = LoggerFactory.getLogger(TestController.class.getName());

    @Autowired
    private SysConfigService sysConfigService;

    @RequestMapping(value = "upload")
    @ResponseBody
    public ResponseEntity<Void> upload(@RequestParam("file") MultipartFile file)
    {
        try {
            String uploadPath = sysConfigService.loadSystemModuleConfig().get(0).getUploadPath();
            Long oriFileSize = file.getSize();
            String originalFilename = file.getOriginalFilename();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String newFileName = df.format(date) + "_" + new Random().nextInt(1000) + "." + suffix;
            String dirName = new SimpleDateFormat("yyyyMMdd").format(date);
            //文件路径
            String dstPath = uploadPath + File.separator + dirName ;
            File f = new File(dstPath);
            if (!f.exists()) {
                f.mkdirs();
            }
            if (oriFileSize > 0) {
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image != null)
                {
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(dstPath, newFileName));
                }
            }
            return new ResponseEntity<Void>(true,"上传成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            LOG.error(e.getMessage(),e);
            return new ResponseEntity<Void>(false,"上传失败");
        }
    }
}
